<template>
  <div class="login-container">
    <div class="login-one"></div>
    <div class="login-two">
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">
        <div class="title-container">
          <h3 class="title">隧道人员管理系统</h3>
        </div>

        <el-form-item prop="username">
          <span class="svg-container">
            <svg-icon icon-class="user" />
          </span>
          <el-input ref="username" v-model="loginForm.username" placeholder="用户名" name="username" type="text" tabindex="1" auto-complete="on" />
        </el-form-item>

        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="密码"
            name="password"
            tabindex="2"
            auto-complete="on"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>

        <el-form-item v-if="validationCode" prop="validationCode">
          <span class="svg-container">
            <svg-icon icon-class="validationCode" />
          </span>
          <el-input ref="validationCode" v-model="loginForm.validationCode" placeholder="验证码" name="validationCode" type="text" tabindex="3" auto-complete="off" style="width: 50%" />
          <span class="show-validationCode" @click="GetValidationCode">
            <el-image style="width: 158px; height: 40px" :src="validationCode" fit="fill" />
          </span>
        </el-form-item>

        <el-button :loading="loading" type="primary" style="width: 100%; margin-bottom: 30px" @click.native.prevent="handleLogin">登录</el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
import { GetValidationCode } from '@/api/user'
import train from '@/assets/img/train.png'
import ico from '@/assets/img/ico.png'
import { Message } from 'element-ui'
export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名！'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('请输入密码！'))
      } else {
        callback()
      }
    }
    const validateValidationCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入验证码！'))
      } else {
        callback()
      }
    }
    return {
      trainImg: train,
      logoImg: ico,
      loginForm: {
        username: '',
        password: '',
        validationCode: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        validationCode: [
          {
            required: true,
            trigger: 'blur',
            validator: validateValidationCode
          }
        ]
      },
      loading: false,
      validationCode: '',
      passwordType: 'password',
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true
          this.$store
            .dispatch('user/login', this.loginForm)
            .then(() => {
              // this.$store.dispatch('permission/generateRoutes',
              // this.$router.push({ path: this.redirect || '/' })
              this.$router.push({ path: '/user/dashboard' })
              this.loading = false
            })
            .catch((err) => {
              if (!err.response) {
                Message({
                  message: '服务器连接失败，请稍后再试！',
                  type: 'error',
                  duration: 5 * 1000
                })
                this.loading = false
                return
              }
              if (err.response.status === 500) {
                Message({
                  message: '服务器连接失败，请稍后再试！',
                  type: 'error',
                  duration: 5 * 1000
                })
                this.loading = false
                return
              }
              if (err.response.data.message === 'ValidateionCodeError') {
                if (this.validationCode) {
                  Message({
                    message: '验证码错误！',
                    type: 'error',
                    duration: 5 * 1000
                  })
                } else {
                  Message({
                    message: '登录失败！',
                    type: 'error',
                    duration: 5 * 1000
                  })
                }
              } else if (err.response.data.code === 401) {
                Message({
                  message: '用户名或密码错误！',
                  type: 'error',
                  duration: 5 * 1000
                })
              } else {
                Message({
                  message: '登陆失败！',
                  type: 'error',
                  duration: 5 * 1000
                })
              }
              this.GetValidationCode()

              // let message = '用户名或密码错误！'
              // if (error.message === "Network Error") {
              //   this.$message({
              //     message: '登陆失败！',
              //     type: 'error',
              //     duration: 5 * 1000
              //   })
              //   this.loading = false
              // }
              // if (error.response.data.message === 'ValidateionCodeError') {
              //   this.GetValidationCode()
              //   message = '验证码错误！'
              // }
              // this.$message({
              //   message: message,
              //   type: 'error',
              //   duration: 5 * 1000
              // })
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    async GetValidationCode() {
      const res = await GetValidationCode()
      this.validationCode = res.data
    }
  }
}
</script>

<style lang="scss">
  /* 修复input 背景不协调 和光标变色 */
  /* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

  $bg: #e5e5e5;
  $light_gray: #586aa6;
  $cursor: #fff;

  @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
    .login-container .el-input input {
      color: $cursor;
    }
  }

  /* reset element-ui css */
  .login-container {
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;

      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: #586aa6;
        height: 47px;
        caret-color: #586aa6;

        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: #586aa6 !important;
        }
      }
    }

    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }
</style>

<style lang="scss" scoped>
  $bg: #fff;
  $dark_gray: #889aa4;
  $light_gray: #eee;

  .login-container {
    min-height: 100%;
    width: 100%;
    background-color: $bg;
    overflow: hidden;
    display: flex;

    .login-one {
      flex: 3;
      background: url('../../assets/img/train.png') no-repeat;
      background-size: 100% 100%;
    }

    .login-two {
      flex: 2;
      display: flex;
      justify-content: center;

      .login-form {
        position: relative;
        width: 420px;
        max-width: 100%;
        margin-top: 220px;
        overflow: hidden;
      }

      .svg-container {
        padding: 6px 5px 6px 15px;
        color: $dark_gray;
        vertical-align: middle;
        width: 30px;
        display: inline-block;
      }

      .title-container {
        position: relative;

        .title {
          font-size: 26px;
          color: #586aa6;
          margin: 0px auto 40px auto;
          text-align: center;
          font-weight: bold;
        }
      }

      .show-pwd {
        position: absolute;
        right: 10px;
        top: 7px;
        font-size: 16px;
        color: $dark_gray;
        cursor: pointer;
        user-select: none;
      }

      .show-validationCode {
        position: absolute;
        top: 0;
        right: 0;
        height: 52px;
        padding: 6px;
      }
    }
  }
</style>
